package com.swust;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.time.LocalDate;

public class MybatisDemo02 {
    @Test
    public void testInsertStudent(){
        InputStream resourceAsStream = MybatisDemo02.class.getClassLoader().getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.insert("test.insertStudent", new Student("GYQ","男", LocalDate.parse("1999-01-01")));
            sqlSession.commit();
        } catch (Exception e) {
           sqlSession.rollback();//如果发送异常则回滚到插入之前
            e.printStackTrace();
        }
        finally {
            sqlSession.close();
        }
    }
    @Test
    public void testUpdateStudent(){
        InputStream is=MybatisDemo02.class.getClassLoader().getResourceAsStream("sqlMapconfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.update("test.updataStudent",new Student(201215121,"GYQ","男",LocalDate.parse("2003-11-01")));
            sqlSession.commit();
        } catch (Exception e) {
         sqlSession.rollback();
            e.printStackTrace();
        }
        finally {
            sqlSession.close();
        }

    }
}
